<template>
	<view class="container">
		<!-- 自定义导航栏 - 小程序适配版本 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content"
				:style="{ height: navBarHeight + 'px', paddingRight: menuButtonInfo.width + menuButtonInfo.right - windowWidth + 10 + 'px' }">
				<view class="scan-btn" @click="scanCode">
					<u-icon name="scan" size="20" color="#fff"></u-icon>
				</view>
				<view class="search-box" @click="goSearch">
					<u-icon name="search" size="16" color="#999"></u-icon>
					<text class="search-text">搜索商品/商家</text>
				</view>
				<view class="nav-right">

					<view class="message-btn" @click="goMessage">
						<u-icon name="bell" size="20" color="#fff"></u-icon>
						<view class="message-dot" v-if="hasNewMessage"></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 轮播图 -->
		<view class="banner-section">
			<swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500" 
				:circular="true" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#fff"
				@change="onBannerChange">
				<swiper-item v-for="(item, index) in bannerList" :key="index">
					<image :src="defaults.defaults.baseUrl + item.image" class="banner-image"
						mode="aspectFill" @click="previewBannerImage(index)"></image>
				</swiper-item>
			</swiper>
			<!-- 图片数量显示 -->
			<view class="banner-count" v-if="bannerList.length > 1">
				<text class="count-text">{{ currentBannerIndex + 1 }}/{{ bannerList.length }}</text>
			</view>
		</view>

		<!-- 公告资讯 -->
		<view class="notice-section" v-if="noticeList.length > 0">
			<view class="notice-content">
				<text class="notice-label">优享优品资讯</text>
				<image :src="getImageUrl('img/remen@3x.png')" class="hot-tag" mode="aspectFit"></image>
				<swiper class="notice-swiper" vertical circular autoplay :interval="3000">
					<swiper-item v-for="(item, index) in noticeList" :key="index">
						<text class="notice-text" @click="goNoticeDetail(item)">{{ item.title }}</text>
					</swiper-item>
				</swiper>
			</view>
		</view>

		<!-- 分类菜单 -->
		<view class="category-section">
			<swiper class="category-swiper" :indicator-dots="false" @change="swiperChange">
				<swiper-item>
					<view class="category-grid">
						<view class="category-item" v-for="(cat, idx) in categories.slice(0, 10)" :key="idx"
							@click="goCategory(cat)">
							<image :src="defaults.defaults.baseUrl + cat.file_path" class="category-icon"></image>
							<text class="category-name">{{ cat.name }}</text>
						</view>
					</view>
				</swiper-item>
				<swiper-item v-if="categories.length > 10">
					<view class="category-grid">
						<view class="category-item" v-for="(cat, idx) in categories.slice(10)" :key="idx"
							@click="goCategory(cat)">
							<image :src="defaults.defaults.baseUrl + cat.file_path" class="category-icon"></image>
							<text class="category-name">{{ cat.name }}</text>
						</view>
					</view>
				</swiper-item>
			</swiper>

			<!-- 自定义指示器 -->
			<view class="custom-indicator">
				<view v-for="(item, index) in swiperPages" :key="index"
					:class="['indicator-dot', currentSwiperIndex === index ? 'active' : '']"></view>
			</view>
		</view>

		<!-- 商品楼层 -->
		<view class="goods-floor-new" v-for="(floor, floorIndex) in goodsFloors" :key="floorIndex">
			<!-- 楼层商品 -->
			<view class="floor-goods-wrapper">
				<!-- 第一个横图 -->
				<view class="goods-item-new first-item" v-if="floor.goods && floor.goods.length > 0"
					@click="handleGoodsClick(floor.goods[0], 0, floor)">
					<view class="goods-image-wrapper-new">
						<image :src="defaults.defaults.baseUrl + floor.goods[0].image" class="goods-image-new" 
							mode="widthFix">
						</image>
						<view class="goods-tag" v-if="floor.goods[0].tag">{{ floor.goods[0].tag }}</view>
					</view>
				</view>
				<!-- 其他小图 -->
				<view class="goods-grid" v-if="floor.goods && floor.goods.length > 1">
					<view class="goods-item-new" v-for="(item, index) in floor.goods.slice(1)" :key="index + 1"
						@click="handleGoodsClick(item, index + 1, floor)">
						<view class="goods-image-wrapper-new">
							<image :src="defaults.defaults.baseUrl + item.image" class="goods-image-new" 
								mode="aspectFit">
							</image>
							<view class="goods-tag" v-if="item.tag">{{ item.tag }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 为您推荐标题 -->
		<view class="recommend-title" v-if="productList.length > 0">
			<view class="recommend-title-dot"></view>
			<text class="recommend-title-text">为您推荐</text>
			<view class="recommend-title-dot"></view>
		</view>

		<!-- 为您推荐商品列表 -->
		<view class="recommend-products" v-if="productList.length > 0">
			<view class="product-grid">
				<template v-for="(item, index) in productList" :key="index">
					<!-- 广告项 -->
					<view class="ad-item-inline" v-if="item.type === 'ad'" @click="handleAdClick(item.adData)">
						<image :src="defaults.defaults.baseUrl + item.adData.file_path" class="ad-image-inline" mode="widthFix"></image>
					</view>
					<!-- 商品项 -->
					<view class="product-item" v-else @click="goProductDetail(item)">
						<view class="product-image-wrapper">
							<image :src="defaults.defaults.baseUrl + item.image" class="product-image" mode="aspectFill">
							</image>
							<view class="activity-label" v-if="item.activityLabel">{{ item.activityLabel }}</view>
						</view>
						<view class="product-info">
							<text class="product-title">{{ item.title }}</text>
							<view class="product-profit" v-if="item.maxProfit && item.maxProfit !== '0.00'">
								<text class="profit-text">分润 ¥{{ item.minProfit }}-{{ item.maxProfit }}</text>
							</view>
							<view class="product-price">
								<text class="current-price">¥{{ item.price }}</text>
							</view>
						</view>
					</view>
				</template>
			</view>
		</view>

		<!-- 上拉加载更多 -->
		<view class="load-more" v-if="showLoadMore">
			<text class="load-text">{{ loadMoreText }}</text>
		</view>

		<!-- 底部提示 -->
		<view class="footer-tip" v-if="showFooterTip && false">
			<view class="tip-content">
				<image src="/static/logo.png" class="tip-logo"></image>
				<view class="tip-text">
					<text class="tip-title">优享优品</text>
					<text class="tip-desc">全民"分润"电商平台</text>
				</view>
				<view class="tip-btn" @click="followApp">
					<text>关注</text>
				</view>
			</view>
		</view>

		<!-- 动态底部导航 -->
		<dynamic-tabbar></dynamic-tabbar>

	</view>
</template>

<script>
import api from '@/api/index.js'
import {
	inject
} from 'vue'
import DynamicTabbar from '@/components/dynamic-tabbar.vue'

export default {
	components: {
		DynamicTabbar
	},
	data() {
		return {
			// 小程序适配相关
			statusBarHeight: 0,
			navBarHeight: 44,
			menuButtonInfo: {},
			windowWidth: 375,
			// 原有数据
			hasNewMessage: false,
			showFooterTip: true,
			bannerList: [],
			categories: [],
			noticeList: [],
			goodsFloors: [],
			showTodayProfit: true,
			showLoadMore: false,
			showLocationPopup: false,
			currentLocation: '北京市',
			selectedLocation: '北京市朝阳区',
			todayProfit: '12,345.67',
			expectedProfit: '23,456.78',
			loadMoreText: '上拉加载更多',
			currentSwiperIndex: 0, // 当前轮播索引
			swiperPages: [1, 2], // 轮播页数
			currentBannerIndex: 0, // 当前轮播图索引
			productList: [],
			currentPage: 1, // 当前页数
			hasMore: true, // 是否还有更多数据
			loading: false,
			defaults: inject('$defaults')
		}
	},
	onLoad() {
		this.initMiniProgramAdapt()
		this.loadData()
		// this.defaults = inject('$defaults') // 注入全局变量
	},
	onPullDownRefresh() {
		this.loadData()
		setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 1000)
	},
	onReachBottom() {

		// 如果正在加载或没有更多数据，直接返回
		if (this.showLoadMore || this.loading || !this.hasMore) {
			return
		}

		this.showLoadMore = true
		this.loading = true
		this.loadMoreText = '加载中...'

		// 页数加1
		this.currentPage += 1

		// 使用与首次加载相同的接口
		api.systemApi.getCateGoods({
			pages: this.currentPage,
			ad_page: Math.ceil(this.currentPage / 2) || 1
		}).then(res => {
			if (res.r === 0 && res.data && res.data.list && res.data.list.length > 0) {
				const newProducts = res.data.list.map(item => {
					const maxProfit = parseFloat(item.rebate_price || item.maxProfit || 0)
					const minProfit = parseFloat(item.min_rebate_price || item.minProfit || maxProfit * 0.6)
					return {
						id: item.goods_id || item.id,
						title: item.goods_name || item.title,
						image: item.file_path || item.image,
						price: item.sale_price || item.price,
						originalPrice: item.market_price || item.originalPrice,
						maxProfit: maxProfit.toFixed(2),
						minProfit: minProfit.toFixed(2),
						handPrice: item.hand_price || '',
						huafan: item.huafan || '',
						goodsSpec: item.goods_spec || '',
						activityLabel: item.activity_label || ''
					}
				})
				
				
				// 追加新数据到现有列表后面
				this.productList = [...this.productList, ...newProducts]
				

				// 处理广告数据 - 将广告插入到新加载的商品后面
				if (res.data.ad && res.data.ad.data && res.data.ad.data.goods && res.data.ad.data.goods.length > 0) {
					res.data.ad.data.goods.forEach(ad => {
						this.productList.push({
							type: 'ad',
							adData: ad
						})
					})
				}

				// 检查是否还有更多数据
				// 只有当返回的数据为空时，才认为没有更多数据
				if (res.data.list.length === 0) {
					this.hasMore = false
					this.loadMoreText = '没有更多了'
				} else {
					// 即使返回的数据少于10条，也继续尝试加载下一页
					this.hasMore = true
					this.loadMoreText = '上拉加载更多'
				}
				this.showLoadMore = false
				this.loading = false
			} else {
				// 主接口失败，降级到o2o推荐接口
				api.o2oApi.forYouPush({
					page: this.currentPage,
					limit: 10,
					latitude: 0,
					longitude: 0
				}).then(fallbackRes => {
					if (fallbackRes.r === 0 && fallbackRes.data && fallbackRes.data.list && fallbackRes.data.list.length > 0) {
						const newProducts = fallbackRes.data.list.map(item => {
							const maxProfit = parseFloat(item.max_profit || item.maxProfit || 0)
							const minProfit = parseFloat(item.min_profit || item.minProfit || maxProfit * 0.6)
							return {
								id: item.goods_id || item.id,
								title: item.goods_name || item.title,
								image: item.goods_image || item.image,
								price: item.shop_price || item.price,
								originalPrice: item.market_price || item.originalPrice,
								maxProfit: maxProfit.toFixed(2),
								minProfit: minProfit.toFixed(2)
							}
						})
						
						// 追加新数据到现有列表后面
						this.productList = [...this.productList, ...newProducts]

						// 检查是否还有更多数据
						if (fallbackRes.data.list.length === 0) {
							this.hasMore = false
							this.loadMoreText = '没有更多了'
						} else {
							this.hasMore = true
							this.loadMoreText = '上拉加载更多'
						}
						this.showLoadMore = false
						this.loading = false
					} else {
						// 没有数据，回退页数
						this.currentPage -= 1
						this.hasMore = false
						this.loadMoreText = '没有更多了'
						this.showLoadMore = false
						this.loading = false
					}
				}).catch(fallbackErr => {
					console.error('降级接口也失败:', fallbackErr)
					this.currentPage -= 1
					this.loadMoreText = '加载失败，点击重试'
					this.showLoadMore = false
					this.loading = false
				})
			}
		}).catch(err => {
			console.error('加载更多失败:', err)
			// 出错时回退页数
			this.currentPage -= 1
			this.loadMoreText = '加载失败，点击重试'
			this.showLoadMore = false
			this.loading = false
		})
	},
	methods: {
		// 小程序适配初始化
		initMiniProgramAdapt() {
			// 获取系统信息
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
			this.windowWidth = systemInfo.windowWidth || 375

			// 获取胶囊按钮信息（仅小程序）
			// #ifdef MP
			try {
				this.menuButtonInfo = uni.getMenuButtonBoundingClientRect() || {
					width: 87,
					height: 32,
					top: this.statusBarHeight + 6,
					right: 7,
					bottom: this.statusBarHeight + 38,
					left: this.windowWidth - 94
				}
				this.navBarHeight = this.menuButtonInfo.height + (this.menuButtonInfo.top - this.statusBarHeight) * 2
			} catch (e) {
				console.error('获取胶囊按钮信息失败:', e)
				this.menuButtonInfo = {
					width: 87,
					height: 32,
					top: this.statusBarHeight + 6,
					right: 7,
					bottom: this.statusBarHeight + 38,
					left: this.windowWidth - 94
				}
				this.navBarHeight = 44
			}
			// #endif

			// #ifndef MP
			this.menuButtonInfo = {
				width: 0,
				height: 0,
				top: 0,
				right: 0,
				bottom: 0,
				left: 0
			}
			// #endif
		},

		// 加载数据
		async loadData() {
			this.loading = true
			try {
				// 首先加载首页数据（包含轮播图、分类、商品楼层等）
				await this.loadHomeData()
				// 然后并行加载其他数据
				await Promise.all([
					this.loadProducts()
					// 移除登录验证相关的数据加载
					// this.checkNewMessage(),
					// this.loadTodayProfit()
				])
			} catch (error) {
				console.error('加载数据失败:', error)
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				})
			} finally {
				// 延迟一下再设置loading为false，确保loadProducts中的状态设置生效
				setTimeout(() => {
					this.loading = false
				}, 100)
			}
		},

		// 加载首页数据
		async loadHomeData() {
			try {
				const result = await api.systemApi.getHomeData()
				if (result.r === 0) {
					// 轮播图数据
					if (result.data.Carousel && result.data.Carousel.length > 0) {
						this.bannerList = result.data.Carousel.map(item => ({
							id: item.id,
							image: item.image || item.file_path,
							url: item.url || item.link_url,
							title: item.title || item.name,
							action: item.action, // 跳转类型
							rel_id: item.rel_id // 关联ID（商品ID、分类ID等）
						}))
					}

					// 分类数据
					if (result.data.category && result.data.category.length > 0) {
						this.categories = result.data.category
						// 计算轮播页数
						this.swiperPages = this.categories.length > 10 ? [1, 2] : [1]
					}

					// 公告数据
					if (result.data.forum && result.data.forum.length > 0) {
						this.noticeList = result.data.forum
					}

					// 商品楼层数据
					if (result.data.list && result.data.list.length > 0) {
						// 处理原系统的商品楼层数据结构
						this.goodsFloors = result.data.list.map(floor => {
							// 根据tpl_id确定楼层类型
							let type = 'recommend'
							if (floor.tpl_id === 1) type = 'banner'
							else if (floor.tpl_id === 2) type = 'two_items'
							else if (floor.tpl_id === 3) type = 'three_items'
							else if (floor.tpl_id === 4) type = 'four_items'
							else if (floor.tpl_id === 5) type = 'five_items'
							else if (floor.tpl_id === 6) type = 'brand_items'
							else if (floor.tpl_id === 7) type = 'six_items'
							else if (floor.tpl_id === 8) type = 'video_items'

							// 获取第一个商品的rel_id作为楼层的rel_id
							const firstGoods = floor.goods && floor.goods[0]
							const rel_id = firstGoods ? firstGoods.rel_id : ''

							return {
								id: floor.id,
								title: floor.name,
								titleImage: floor.file_path,
								type: type,
								tpl_id: floor.tpl_id,
								is_show_name: floor.is_show_name,
								rel_id: rel_id, // 添加rel_id字段
								goods: (floor.goods || []).map(item => ({
									id: item.goods_id || item.id,
									title: item.goods_name || item.title,
									image: item.goods_image || item.image || item.file_path,
									price: item.shop_price || item.price,
									originalPrice: item.market_price || item.originalPrice,
									maxProfit: item.max_profit || item.maxProfit || '0.00',
									action: item.action, // 保留原系统的跳转逻辑
									rel_id: item.rel_id // 保留商品的rel_id
								}))
							}
						})
					}
				} else {
					console.error('获取首页数据失败:', result.msg)
				}
			} catch (error) {
				console.error('加载首页数据失败:', error)
				// 加载备用数据
				this.loadBanners()
				this.loadCategories()
				this.loadGoodsFloorsBackup()
			}
		},

		// 加载轮播图
		async loadBanners() {
			try {
				const result = await api.systemApi.getBannerList()
				if (result.r === 0) {
					this.bannerList = result.data.map(item => ({
						id: item.id,
						image: item.image_url,
						url: item.link_url,
						title: item.title,
						action: item.action,
						rel_id: item.rel_id
					}))
				} else {
					console.error('获取轮播图失败:', result.msg)
				}
			} catch (error) {
				console.error('加载轮播图失败:', error)
				// 模拟数据
				this.bannerList = [
					{ id: 1, image: '/static/banner1.jpg', url: '' },
					{ id: 2, image: '/static/banner2.jpg', url: '' }
				]
			}
		},

		// 加载商品列表
		async loadProducts() {
			try {
				// 重置分页状态
				this.currentPage = 1
				this.hasMore = true
				this.loading = false // 确保loading状态正确
				this.showLoadMore = false // 确保showLoadMore状态正确

				// 使用新的 cateGoods 接口获取为您推荐商品
				const result = await api.systemApi.getCateGoods({
					pages: this.currentPage,
					ad_page: 1
				})
				if (result.r === 0 && result.data && result.data.list) {
					this.productList = result.data.list.map(item => {
						const maxProfit = parseFloat(item.rebate_price || item.maxProfit || 0)
						const minProfit = parseFloat(item.min_rebate_price || item.minProfit || maxProfit * 0.6)
						return {
							id: item.goods_id || item.id,
							title: item.goods_name || item.title,
							image: item.file_path || item.image,
							price: item.sale_price || item.price,
							originalPrice: item.market_price || item.originalPrice,
							maxProfit: maxProfit.toFixed(2),
							minProfit: minProfit.toFixed(2),
							handPrice: item.hand_price || '',
							huafan: item.huafan || '',
							goodsSpec: item.goods_spec || '',
							activityLabel: item.activity_label || ''
						}
					})

					// 处理广告数据 - 将广告插入到商品列表中
					if (result.data.ad && result.data.ad.data && result.data.ad.data.goods && result.data.ad.data.goods.length > 0) {
						result.data.ad.data.goods.forEach(ad => {
							this.productList.push({
								type: 'ad',
								adData: ad
							})
						})
					}

					// 检查是否还有更多数据
					// 只有当返回的数据为空时，才认为没有更多数据
					if (result.data.list.length === 0) {
						this.hasMore = false
						} else {
						// 即使返回的数据少于10条，也继续尝试加载下一页
						// 因为可能接口分页不准确，或者确实还有数据
						this.hasMore = true
						}
				} else {
					console.error('获取为您推荐商品失败:', result.msg)
					// 降级到o2o推荐接口
					const fallbackResult = await api.o2oApi.forYouPush({
						page: this.currentPage,
						limit: 10,
						latitude: 0,
						longitude: 0
					})
					if (fallbackResult.r === 0 && fallbackResult.data && fallbackResult.data.list) {
						this.productList = fallbackResult.data.list.map(item => {
							const maxProfit = parseFloat(item.max_profit || item.maxProfit || 0)
							const minProfit = parseFloat(item.min_profit || item.minProfit || maxProfit * 0.6)
							return {
								id: item.goods_id || item.id,
								title: item.goods_name || item.title,
								image: item.goods_image || item.image,
								price: item.shop_price || item.price,
								originalPrice: item.market_price || item.originalPrice,
								maxProfit: maxProfit.toFixed(2),
								minProfit: minProfit.toFixed(2)
							}
						})
						// 检查是否还有更多数据
						if (fallbackResult.data.list.length === 0) {
							this.hasMore = false
						} else {
							this.hasMore = true
						}
					} else {
						console.error('获取商品列表失败:', fallbackResult.msg)
						this.hasMore = false
					}
				}
			} catch (error) {
				console.error('加载商品列表失败:', error)
				this.hasMore = false
			}
		},

		// 加载商品楼层（降级接口）
		async loadGoodsFloorsBackup() {
			try {
				const result = await api.goodsApi.getGoodsFloors()
				if (result.r === 0 && result.data) {
					this.goodsFloors = result.data.map(floor => ({
						id: floor.id,
						title: floor.title,
						titleImage: floor.title_image,
						type: floor.type || 'recommend',
						moreUrl: floor.more_url,
						goods: (floor.goods || []).map(item => ({
							id: item.goods_id || item.id,
							title: item.goods_name || item.title,
							image: item.goods_image || item.image,
							price: item.shop_price || item.price,
							originalPrice: item.market_price || item.originalPrice,
							maxProfit: item.max_profit || item.maxProfit || '0.00',
							tag: item.tag || item.goods_tag
						}))
					}))
				} else {
					console.error('获取商品楼层失败:', result.msg)
				}
			} catch (error) {
				console.error('加载商品楼层失败:', error)
			}
		},

		// 加载今日分润数据
		async loadTodayProfit() {
			try {
				// 检查用户是否登录
				const userInfo = uni.getStorageSync('user_info')
				if (!userInfo || !userInfo.token) {
					// 未登录用户不显示分润信息
					this.showTodayProfit = false
					return
				}

				const result = await api.profitApi.getTodayProfit()
				if (result.r === 0 && result.data) {
					this.todayProfit = result.data.today_profit || '0.00'
					this.expectedProfit = result.data.expected_profit || '0.00'
					this.showTodayProfit = true
				} else {
					console.error('获取今日分润失败:', result.msg)
					this.showTodayProfit = false
				}
			} catch (error) {
				console.error('加载今日分润失败:', error)
				this.showTodayProfit = false
			}
		},

		// 检查新消息
		async checkNewMessage() {
			try {
				// 检查用户是否登录
				const userInfo = uni.getStorageSync('user_info')
				if (userInfo && userInfo.token) {
					// 已登录用户检查新消息
					const messageResult = await api.systemApi.checkNewMessage()
					if (messageResult.r === 0 && messageResult.data) {
						this.hasNewMessage = messageResult.data.hasNew || false
					}
				}

				// 获取公告列表（所有用户都可以看到）
				const noticeResult = await api.systemApi.getNoticeList()
				if (noticeResult.r === 0 && noticeResult.data && noticeResult.data.length > 0) {
					this.noticeList = noticeResult.data.map(item => ({
						id: item.id,
						title: item.title || item.content,
						url: item.url || '',
						create_time: item.create_time
					}))
				} else {
					// 设置默认公告
					this.noticeList = [
						{ id: 1, title: '优享优品平台正式上线，欢迎体验！', url: '' },
						{ id: 2, title: '新用户注册即送优惠券，快来领取吧！', url: '' }
					]
				}
			} catch (error) {
				console.error('检查新消息失败:', error)
				// 设置默认数据
				this.hasNewMessage = false
				this.noticeList = [
					{ id: 1, title: '优享优品平台正式上线，欢迎体验！', url: '' },
					{ id: 2, title: '新用户注册即送优惠券，快来领取吧！', url: '' }
				]
			}
		},

		// 显示地区选择
		showLocationPicker() {
			this.showLocationPopup = true
		},

		// 重新定位
		relocate() {
			uni.showLoading({
				title: '定位中...'
			})
			uni.getLocation({
				type: 'gcj02',
				isHighAccuracy: true,
				success: (res) => {
					// 这里可以调用逆地理编码API获取地址信息
					// 暂时使用模拟数据
					this.selectedLocation = '当前位置'
					uni.hideLoading()
					uni.showToast({
						title: '定位成功',
						icon: 'success'
					})
				},
				fail: (err) => {
					console.error('定位失败:', err)
					uni.hideLoading()
					uni.showToast({
						title: '定位失败，请检查定位权限',
						icon: 'none',
						duration: 2000
					})
				}
			})
		},

		// 确认地区选择
		confirmLocation() {
			this.currentLocation = this.selectedLocation
			this.showLocationPopup = false
			// 重新加载数据
			this.loadData()
		},

		// 扫码
		scanCode() {
			uni.scanCode({
				success: (res) => {
					// TODO: 处理扫码结果
				}
			})
		},

		// 跳转搜索
		goSearch() {
			uni.navigateTo({
				url: '/pages/search/index'
			})
		},

		// 跳转消息
		goMessage() {
			uni.navigateTo({
				url: '/pages/news/list'
			})
		},

		// 轮播图点击
		bannerClick(item) {
			if (!item) return

			// 优先处理 action 和 rel_id 的组合跳转
			if (item.action !== undefined && item.rel_id) {
				// action: 1-商品详情, 2-分类列表, 3-专区, 4-外部链接
				if (item.action === 1) {
					// 跳转到商品详情
					uni.navigateTo({
						url: `/pages/goods/detail?id=${item.rel_id}&title=${encodeURIComponent(item.title || '')}`
					})
				} else if (item.action === 2) {
					// 跳转到分类列表
					uni.navigateTo({
						url: `/pages/product/list?id=${item.rel_id}&level=2`
					})
				} else if (item.action === 3) {
					// 跳转到专区
					uni.navigateTo({
						url: `/pages/activity/zone?id=${item.rel_id}&title=${encodeURIComponent(item.title || '专区')}`
					})
				} else if (item.action === 4 && item.url) {
					// 外部链接，使用 web-view 打开
					uni.navigateTo({
						url: `/pages/public/commonWeb?url=${encodeURIComponent(item.url)}&title=${encodeURIComponent(item.title || '')}`
					})
				}
			} else if (item.url) {
				// 处理URL跳转
				let targetUrl = item.url
				
				// 处理网站格式的URL，转换为小程序路由
				// 例如: /view/productdetail.html?goodsid=28458 -> /pages/goods/detail?id=28458
				if (targetUrl.includes('/view/productdetail.html')) {
					const match = targetUrl.match(/goodsid=(\d+)/)
					if (match && match[1]) {
						targetUrl = `/pages/goods/detail?id=${match[1]}&title=${encodeURIComponent(item.title || '')}`
					}
				}
				// 处理其他网站格式的URL
				else if (targetUrl.includes('/view/') && !targetUrl.startsWith('http')) {
					// 如果是相对路径的view格式，尝试转换为小程序路由
					if (targetUrl.includes('productdetail')) {
						const match = targetUrl.match(/goodsid=(\d+)/)
						if (match && match[1]) {
							targetUrl = `/pages/goods/detail?id=${match[1]}&title=${encodeURIComponent(item.title || '')}`
						}
					}
				}
				
				// 判断是内部路径还是外部链接
				if (targetUrl.startsWith('http://') || targetUrl.startsWith('https://')) {
					// 外部链接
					uni.navigateTo({
						url: `/pages/public/commonWeb?url=${encodeURIComponent(targetUrl)}&title=${encodeURIComponent(item.title || '')}`
					})
				} else if (targetUrl.startsWith('/pages/')) {
					// 内部页面路径
					uni.navigateTo({
						url: targetUrl
					})
				} else {
					// 其他情况，尝试作为内部路径处理
					uni.navigateTo({
						url: targetUrl
					})
				}
			} else if (item.rel_id) {
				// 只有 rel_id，默认跳转到商品详情
				uni.navigateTo({
					url: `/pages/goods/detail?id=${item.rel_id}&title=${encodeURIComponent(item.title || '')}`
				})
			}
		},

		// 公告详情
		goNoticeDetail(item) {
			if (item.url && item.url.startsWith('/pages/')) {
				// 如果有自定义URL，直接跳转
				uni.navigateTo({
					url: item.url
				})
			} else {
				// 默认跳转到新闻详情页
				uni.navigateTo({
					url: `/pages/news/detail?id=${item.id}&title=${encodeURIComponent(item.title || '')}`
				})
			}
		},

		// 菜单点击
		menuClick(item) {
			if (item.url) {
				uni.navigateTo({
					url: item.url
				})
			}
		},

		// 加入平台
		joinPlatform() {
			// 检查用户是否已登录
			const userInfo = uni.getStorageSync('user_info')
			if (!userInfo || !userInfo.token) {
				// 未登录，跳转到登录页
				uni.navigateTo({
					url: '/pages/login/login'
				})
				return
			}

			// 已登录，跳转到身份申请页
			uni.navigateTo({
				url: '/pages/identity/apply'
			})
		},

		// 商品详情
		goProductDetail(item) {
			// 优先使用 rel_id，如果没有则使用 id
			const goodsId = item.rel_id || item.id
			uni.navigateTo({
				url: `/pages/goods/detail?id=${goodsId}&title=${encodeURIComponent(item.title || '')}`
			})
		},

		// 广告点击处理
		handleAdClick(ad) {
			// 根据广告的action类型进行不同的跳转处理
			if (ad.action === 1 && ad.url) {
				// 跳转到指定URL
				uni.navigateTo({
					url: ad.url
				})
			} else if (ad.rel_id) {
				// 跳转到商品详情或其他页面
				uni.navigateTo({
					url: `/pages/goods/detail?id=${ad.rel_id}`
				})
			}
		},

		// 处理商品点击事件
		handleGoodsClick(item, index, floor) {
			// 判断楼层商品数量，决定跳转逻辑
			if (floor.goods && floor.goods.length === 1) {
				// 只有一个商品时，使用原有的handleGoodsClick逻辑
				if (index === 0) {
					// 使用楼层的action作为专区ID
					const zoneId = floor.rel_id || ''
					uni.navigateTo({
						url: `/pages/activity/zone?id=${zoneId}&title=${encodeURIComponent(floor.title || '专区')}`
					})
				} else {
					// 其他商品跳转到商品详情页
					this.goProductDetail(item)
				}
			} else {
				// 多个商品时
				if (index === 0) {
					// 第一个商品跳转到商品列表页，使用 rel_id 作为分类ID
					const categoryId = item.rel_id || floor.rel_id || ''
					uni.navigateTo({
						url: `/pages/product/list?id=${categoryId}&level=2`
					})
				} else {
					// 其他商品跳转到商品详情页
					this.goProductDetail(item)
				}
			}
		},

		// 楼层更多商品
		goFloorMore(floor) {
			if (floor.moreUrl) {
				uni.navigateTo({
					url: floor.moreUrl
				})
			} else {
				// 默认跳转到商品列表页
				uni.navigateTo({
					url: `/pages/product/list?floorType=${floor.type}&floorTitle=${encodeURIComponent(floor.title || '')}&level=2`
				})
			}
		},

		// 更多商品
		goMore() {
			uni.switchTab({
				url: '/pages/classification/index'
			})
		},

		// 关注应用
		followApp() {
			this.showFooterTip = false
		},
		async loadCategories() {
			try {
				// 优先使用首页数据中的分类，如果没有则单独请求
				if (this.categories.length === 0) {
					// 使用原系统的o2o分类接口
					const res = await api.o2oApi.getTopCateList()
					if (res.r === 0 && res.data) {
						this.categories = res.data.map(item => ({
							id: item.id || item.cat_id,
							name: item.name || item.cat_name,
							file_path: item.file_path || item.icon || item.image,
							url: item.url || '',
							sort_order: item.sort_order || 0
						}))

						// 添加生活服务入口
						this.categories.unshift({
							id: 'life',
							name: '生活',
							file_path: '/static/tabbar/life.svg',
							url: '/pages/o2o/index',
							sort_order: -1
						})

						// 计算轮播页数
						this.swiperPages = this.categories.length > 10 ? [1, 2] : [1]
					} else {
						console.error('获取o2o分类失败:', res.msg)
						// 降级到普通商品分类接口
						const fallbackRes = await api.goodsApi.getGoodsCategory()
						if (fallbackRes.r === 0 && fallbackRes.data) {
							this.categories = fallbackRes.data.map(item => ({
								id: item.id || item.cat_id,
								name: item.name || item.cat_name,
								file_path: item.file_path || item.icon || item.image,
								url: item.url || '',
								sort_order: item.sort_order || 0
							}))

							// 添加生活服务入口
							this.categories.unshift({
								id: 'life',
								name: '生活',
								file_path: '/static/tabbar/life.svg',
								url: '/pages/o2o/index',
								sort_order: -1
							})

							this.swiperPages = this.categories.length > 10 ? [1, 2] : [1]
						} else {
							this.categories = []
						}
					}
				}
			} catch (error) {
				console.error('加载分类失败:', error)
				this.categories = []
			}
		},
		goCategory(cat) {
			// 根据分类信息跳转到对应页面
			if (cat.url && cat.url.startsWith('/pages/')) {
				// 如果有自定义URL，直接跳转
				uni.navigateTo({
					url: cat.url
				})
			} else {
				// 默认跳转到商品列表页
				uni.navigateTo({
					url: `/pages/product/list?id=${cat.id}&level=${cat.level || 2}`
				})
			}
		},

		// 轮播切换事件
		swiperChange(e) {
			this.currentSwiperIndex = e.detail.current;
		},

		// 轮播图切换事件
		onBannerChange(e) {
			this.currentBannerIndex = e.detail.current;
		},

		// 预览轮播图（实际执行跳转）
		previewBannerImage(index) {
			if (this.bannerList.length === 0 || !this.bannerList[index]) return
			// 直接执行跳转逻辑
			this.bannerClick(this.bannerList[index])
		},

		// 获取完整图片URL（拼接server_address前缀）
		getImageUrl(path) {
			if (!path) return ''
			// 如果路径以 http:// 或 https:// 开头，直接返回
			if (path.startsWith('http://') || path.startsWith('https://')) {
				return path
			}
			// 如果路径以 / 开头，说明是本地路径，直接返回
			if (path.startsWith('/')) {
				return path
			}
			// 否则拼接 server_address（图片服务器地址）
			const serverAddress = this.defaults?.defaults?.server_address || 'https://weixin.youpin91.com.cn/'
			// 确保 serverAddress 以 / 结尾，path 不以 / 开头
			const baseUrl = serverAddress.endsWith('/') ? serverAddress : serverAddress + '/'
			const imagePath = path.startsWith('/') ? path.substring(1) : path
			return baseUrl + imagePath
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-top: calc(var(--status-bar-height, 0px) + 44px);
	padding-bottom: calc(50px + env(safe-area-inset-bottom));
}

.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background: linear-gradient(135deg, #FF8033 0%, #FF6B35 100%);

		.navbar-content {
		display: flex;
		align-items: center;
		padding: 0 30rpx;

		.location-text {
			margin: 0 5px;
			color: #fff;
			font-size: 13px;
			max-width: 60px;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.search-box {
			flex: 1;
			height: 56rpx;
			background-color: #ffffff;
			border-radius: 28rpx;
			display: flex;
			align-items: center;
			padding: 0 24rpx;

			.search-text {
				color: #999;
				font-size: 26rpx;
				margin-left: 12rpx;
			}
		}

		.nav-right {
			display: flex;
			align-items: center;
			margin-left: 20rpx;
		}

		.scan-btn,
		.message-btn {
			width: 64rpx;
			height: 64rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 16rpx;
		}

		.message-btn {
			position: relative;

			.message-dot {
				position: absolute;
				top: 12rpx;
				right: 12rpx;
				width: 16rpx;
				height: 16rpx;
				background-color: #ff4757;
				border-radius: 50%;
			}
		}
	}
}

.banner-section {
	padding: 45rpx 30rpx 15rpx;
	position: relative;

	.banner-swiper {
		height: 300rpx;
		border-radius: 12rpx;
		overflow: hidden;

		.banner-image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}
	}

	.banner-count {
		position: absolute;
		bottom: 35rpx;
		right: 50rpx;
		background-color: rgba(0, 0, 0, 0.5);
		padding: 8rpx 16rpx;
		border-radius: 24rpx;

		.count-text {
			font-size: 24rpx;
			color: #fff;
		}
	}
}

.notice-section {
	padding: 6rpx 12rpx;
	background: transparent;
	margin: 10rpx 30rpx 10rpx;
	overflow: visible;
}

.notice-content {
	display: flex;
	align-items: center;
	height: 41rpx;
	width: 100%;
}

.notice-label {
	font-size: 24rpx;
	color: #FF8033FF;
	margin-right: 12rpx;
	font-weight: 500;
	flex-shrink: 0;
	line-height: 41rpx;
	-webkit-font-smoothing: antialiased;
	text-rendering: optimizeLegibility;
}

.hot-tag {
	width: 68rpx;
	height: 36rpx;
	margin-right: 12rpx;
	flex-shrink: 0;
	image-rendering: -webkit-optimize-contrast;
	image-rendering: crisp-edges;
}

.notice-swiper {
	flex: 1;
	height: 41rpx;
	min-width: 0;
}

.notice-swiper ::v-deep .uni-swiper-item {
	height: 41rpx;
	display: flex;
	align-items: center;
	justify-content: flex-start;
}

.notice-text {
	font-size: 22rpx;
	color: #656565;
	line-height: 41rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	display: block;
	width: 100%;
	-webkit-font-smoothing: antialiased;
	text-rendering: optimizeLegibility;
}

.category-section {
	background-color: #fff;
	border-radius: 12rpx;
	margin: 10rpx 30rpx;
	padding: 20rpx 0;
}

.category-grid {
	display: grid;
	grid-template-columns: repeat(5, 1fr);
	border-radius: 6rpx;

	.category-item {
		padding: 8rpx 12rpx 8rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		.category-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.category-name {
			font-size: 22rpx;
			color: #333;
			font-weight: 500;
			margin-top: 8rpx;
		}

		.category-count {
			font-size: 10rpx;
			color: #999;
		}
	}
}

.goods-floor-new {
	margin-bottom: 15rpx;

	.floor-goods-wrapper {
		padding: 0 20rpx;
	}
}

.goods-item-new {
	background: transparent;
	transition: all 0.3s ease;
	display: flex;
	flex-direction: column;

	&:active {
		transform: translateY(-2rpx);

		.goods-image-new {
			transform: scale(1.02);
		}
	}
}

.goods-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;

	.goods-item-new {
		width: calc(33.333% - 8.67rpx);
	}

	.goods-image-wrapper-new {
		aspect-ratio: 1/1;
		display: flex;
		align-items: center;
		justify-content: center;

		.goods-image-new {
			height: 100%;
			object-fit: contain;
		}
	}
}

.goods-image-wrapper-new {
	position: relative;
	width: 100%;
	overflow: hidden;
	background: transparent;
	border-radius: 8rpx;
}

.goods-image-new {
	width: 100%;
	height: auto;
	transition: transform 0.3s ease;
	border-radius: 8rpx;
}

.goods-tag {
	position: absolute;
	top: 8rpx;
	left: 8rpx;
	background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
	color: #fff;
	font-size: 18rpx;
	padding: 4rpx 10rpx;
	border-radius: 12rpx;
	font-weight: 500;
	box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
	z-index: 2;
}

.recommend-title {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 30rpx 30rpx 20rpx;
	gap: 10rpx;

	.recommend-title-dot {
		width: 24rpx;
		height: 24rpx;
		border-radius: 50%;
		background-color: #FF8C00;
	}

	.recommend-title-text {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
	}
}

.recommend-products {
	padding: 0 30rpx 40rpx;

	.product-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 20rpx;
	}

	.ad-item-inline {
		grid-column: 1 / -1;
		width: 100%;
		margin: 20rpx 0;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

		.ad-image-inline {
			width: 100%;
			display: block;
			border-radius: 16rpx;
		}
	}

	.product-item {
		width: 100%;
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;

		.product-image-wrapper {
			position: relative;
			width: calc(100% - 58rpx);
			aspect-ratio: 420.48 / 348.47;
			margin: 35rpx 29rpx 29rpx;
			overflow: hidden;
			background: #fff;
			border-radius: 16rpx 16rpx 0 0;

			.product-image {
				width: 100%;
				height: 100%;
				object-fit: cover;
				border-radius: 16rpx 16rpx 0 0;
			}

			.activity-label {
				position: absolute;
				top: 16rpx;
				left: 16rpx;
				background: rgba(255, 102, 0, 0.9);
				color: #fff;
				font-size: 24rpx;
				padding: 4rpx 16rpx;
				border-radius: 8rpx;
			}
		}

		.product-info {
			padding: 24rpx;
			display: flex;
			flex-direction: column;

			.product-title {
				font-size: 28rpx;
				color: #212121;
				font-weight: 400;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
				position: relative;
				line-height: 35rpx;
				height: 70rpx;
			}

			.product-profit {
				margin: 6rpx 0;

				.profit-text {
					font-size: 24rpx;
					color: #6e6e6e;
				}
			}

			.product-price {
				.current-price {
					font-size: 32rpx;
					color: #ff9600;
					font-weight: 700;
					margin-top: -6rpx;
				}
			}
		}
	}
}

.load-more {
	padding: 15px;
	text-align: center;
	background: #fff;
}

.load-text {
	font-size: 13px;
	color: #999;
}

.custom-indicator {
	display: flex;
	justify-content: center;
	align-items: center;

	.indicator-dot {
		width: 30rpx;
		height: 10rpx;
		border-radius: 6rpx;
		background-color: #ddd;
		margin: 0 4rpx;
		transition: all 0.3s;

		&.active {
			background-color: #ff5722;
			width: 30rpx;
		}
	}
}

</style>
